package com.ruoyi.web.controller.tool;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ExceptionUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.http.HttpClient;
import com.ruoyi.common.utils.http.HttpsClientUtil;
import com.ruoyi.system.utils.DictUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

public class PlGetDataUtils {

    protected static final Logger logger = LoggerFactory.getLogger(PlGetDataUtils.class);


    //各平台接口地址,imes-qyty.roshan88.com;imes-yabotiyu.utoyen.com
    public static String yb_host = "https://imes-qyty.roshan88.com";
    public static String lh_host = "https://api-v4.zixunyx.com";
    public static String ldj_host = "https://gameinfo.365links4ray.com";

    //根据字典设置地址，获取所有比赛时设置
    //雷火token
    static String lh_token = "Token 9278cadf62902610a21cfecfc60b8eeb2c830e93";
    //亚博获取所有比赛
    //PHT队伍1，PAT队伍2
    public static JSONArray get_yb_allMatch(String gameName, List<String> dateList) {
        yb_host = DictUtils.getDictCache("pl_rest_url").get(0).getDictValue();
        Integer game_id = 45;
        if(gameName.equals("英雄联盟")){
            game_id=45;
        }
        if(gameName.equals("Dota")){
            game_id=46;
        }
        if(gameName.equals("CS")){
            game_id=47;
        }
        if(gameName.equals("王者荣耀")){
            game_id=48;
        }
        String lgid = "";
        try {
            lgid = HttpsClientUtil.sendPost(yb_host+"/api/GetActiveBaseLeagueBySport",
                    "{\"SportId\":-99,\"EventMarket\":-99,\"Language\":\"chs\",\"GameCat\":1}");
        }catch (Exception e){
            logger.error("IM获取全部比赛异常！！！gameName="+gameName+">>>异常信息:"+ ExceptionUtil.getExceptionMessage(e));
        }
        JSONObject lgid_json = JSONObject.parseObject(lgid);
        JSONArray sport_json = lgid_json.getJSONArray("Sport");
        List<Integer>  BaseLGIds = new ArrayList<>();
        JSONArray baselgs = new JSONArray();
        for (Object o:sport_json) {
            JSONObject js_sport = JSONObject.parseObject(o.toString());
            if(js_sport.getInteger("SportId")==(game_id)){
                baselgs = js_sport.getJSONArray("BaseLG");
                break;
            }
        }
        for (Object o:baselgs) {
            JSONObject l = JSONObject.parseObject(o.toString());
            if(l.getInteger("BaseLGId")>0){
                BaseLGIds.add(l.getInteger("BaseLGId"));
            }
        }
        String y_str = "";
        try {
            y_str = HttpsClientUtil.sendPost(yb_host+"/api/GetIndexMatch","{\"GameCat\":1,\"SportId\":"+game_id+",\"BaseLGIds\":"+BaseLGIds+",\"EventMarket\":-99,\"MatchCnt\":1000,\"SortType\":1,\"Language\":\"chs\",\"BettingChannel\":1}");
        }catch (Exception e){
            e.printStackTrace();
        }
        JSONObject y_json = JSONObject.parseObject(y_str);
        Object y_report = null;
        try{
            JSONArray sport = y_json.getJSONArray("Sport");
            if(sport==null||sport.size()==0){
                return  new JSONArray();
            }
            y_report  = sport.get(0);
        }catch (Exception e){
            e.printStackTrace();
        }

        JSONArray lg = JSONObject.parseObject(y_report.toString()).getJSONArray("LG");
        JSONArray y_result = new JSONArray();
//        List y_result = new ArrayList();
        for (Object lg_date : lg) {
            JSONObject lg_jsonObject = JSONObject.parseObject(lg_date.toString());
            y_result.addAll(lg_jsonObject.getJSONArray("ParentMatch"));
        }
        //梳理出最近两天的比赛
        JSONArray y_result_near = new JSONArray();
        for (Object yr : y_result){
            JSONObject json = JSONObject.parseObject(yr.toString());
            String startTime=json.getString("PMCDate");
            startTime=startTime.replace("T"," ");
            Date startDate = DateUtils.addHours(DateUtils.parseDate(startTime.substring(0, 19)), 12);
            Date needDateEnd = DateUtils.addDays(new Date(),dateList.size());
            if(startDate.getTime()<needDateEnd.getTime()){
                y_result_near.add(yr);
            }
        }
        return y_result_near;
    }
    //雷电竞获取所有比赛
    //网址：https://www.raybet98.com/match/37211889
    public static JSONArray get_ldj_allMatch(String gameName, List<String> dateList) {
        ldj_host = DictUtils.getDictCache("pl_rest_url").get(2).getDictValue();
        JSONArray l_result = new JSONArray();
        for (int match_type = 0; match_type <= 3; match_type++) {
            JSONArray result = new JSONArray();
            int page = 1;
            try {
                do {
                    String l_str = HttpClient.doGetCloseable(ldj_host+"/v2/match?page=" + page + "&match_type=" + match_type,null);
                    JSONObject l_json = JSONObject.parseObject(l_str);
                    result = l_json.getJSONArray("result");
                    l_result.addAll(result);
                    page++;
                } while (result.size() == 30);
            }catch (Exception e){
                logger.error("雷电竞获取全部比赛异常！！！gameName="+gameName+">>>异常信息:"+ ExceptionUtil.getExceptionMessage(e));
            }
        }
        JSONArray ldj_result = new JSONArray();
        for (Object res:l_result) {
            JSONObject res_json = JSONObject.parseObject(res.toString());
            String startTime = res_json.getString("start_time");
            boolean flag = false;
            for (String date:dateList) {
                String substring = startTime.substring(0, 10);
                if(date.equals(substring)){
                    flag = true;
                    break;
                }
            }
            if(gameName.equals("英雄联盟")){
                if(flag&&res_json.getString("game_id").equals("70")){
                    ldj_result.add(res);
                }
            }
            if(gameName.equals("CS")){
                if(flag&&res_json.getString("game_id").equals("140")){
                    ldj_result.add(res);
                }
            }
            if(gameName.equals("Dota")){
                if(flag&&res_json.getString("game_id").equals("151")){
                    ldj_result.add(res);
                }
            }
            if(gameName.equals("王者荣耀")){
                if(flag&&res_json.getString("game_id").equals("74")){
                    ldj_result.add(res);
                }
            }
        }
        return ldj_result;
    }

    /**
     * 获取雷火所有比赛
     * @return
     *///网址 https://e8198.com/games/esports.html
    public static JSONArray get_lh_allMatch(String gameName,List<String> dateList) {
        lh_host = DictUtils.getDictCache("pl_rest_url").get(1).getDictValue();
        String game_id = "";
        if(gameName!=null&&gameName.equals("CS")){
            game_id = "1";
        }
        if(gameName!=null&&gameName.equals("Dota")){
            game_id = "2";
        }
        if(gameName!=null&&gameName.equals("英雄联盟")){
            game_id = "3";
        }
        if(gameName!=null&&gameName.equals("王者荣耀")){
            game_id = "14";
        }
        /*//暂时只获取今天和明天
        String today = DateUtils.getDate();
        String tomorrow = DateUtils.getNextDay(new Date());
        List<String> dateList = new ArrayList<>();
        dateList.add(today);
        dateList.add(tomorrow);*/
        //设置header token
        Map<String,String> header = new HashMap<>();
        header.put("Authorization",lh_token);
        JSONArray lh_result = new JSONArray();
        for (String date:dateList) {
            int page = 1;
            JSONArray result = new JSONArray();
            try {
                do {
                    //game = 3 英雄联盟
                    String lh_str = HttpClient.doGetCloseable(lh_host+"/api/v4/events/paginate?" +
                            "game_id="+game_id+"&date="+date+"&sort_by_popular=false&timezone=Asia%2FShanghai&combo=false&lang=zh&page="+page ,header);
                    JSONObject lh_json = JSONObject.parseObject(lh_str);
                    result = lh_json.getJSONArray("results");
                    if(StringUtils.isEmpty(result)){
                        break;
                    }
                    lh_result.addAll(result);
                    page++;
                } while (result.size() == 20);
            }catch (Exception e){
                logger.error("雷火获取全部比赛异常！！！gameName="+gameName+">>>异常信息:"+ ExceptionUtil.getExceptionMessage(e));
            }
        }
        return lh_result;
    }

    /*
     // 获取雷火的比赛内容详情接口
    */
    public static JSONObject get_lh_content(String event_id) {
        String zj = "&market_option=MATCH&";
        String j_1 = "&market_option=map&map_option=MAP%201&";
        String j_2 = "&market_option=map&map_option=MAP%202&";
        String j_3 = "&market_option=map&map_option=MAP%203&";
        List<String> j_list = new ArrayList<>();
        j_list.add(zj);
        j_list.add(j_1);
        j_list.add(j_2);
        j_list.add(j_3);
        //设置header token
        Map<String, String> header = new HashMap<>();
        header.put("Authorization", lh_token);
        //收集所有局的赔率
        JSONObject lh_result = new JSONObject();
        JSONArray markets = new JSONArray();
        for (String l_n : j_list) {
            try {
                String l_str = HttpClient.doGetCloseable(lh_host+"/api/v4/events/paginate?" +
                        "event_id=" + event_id + l_n +
                        "timezone=Asia%2FShanghai&combo=false&lang=zh&sort_by_popular=false", header);
                JSONArray results = JSONObject.parseObject(l_str).getJSONArray("results");
                if(results.size()==0){
                    continue;
                }
                lh_result = JSONObject.parseObject(results.get(0).toString());
                JSONArray lh_array = lh_result.getJSONArray("markets");
                markets.addAll(lh_array);
            } catch (Exception e) {
                logger.error("雷火比赛内容详情获取异常！！！event_id="+event_id+">>>异常信息:"+ ExceptionUtil.getExceptionMessage(e));
            }
        }
        lh_result.put("markets", markets);
        return lh_result;
    }

    /*
      // 获取亚博的比赛内容详情接口
     */
    public static JSONObject get_yb_content(String PMatchNo) {
        JSONObject yb = null;
        try {
            String y_str = HttpsClientUtil.sendPost(yb_host+"/api/GetMatchDetailsByParent",
                    "{\"GameCat\":1,PMatchNo: \"" + PMatchNo + "\", Token: null, Language: \"chs\", BettingChannel: 1,\"Grp\":-99,\"GTGrpCnt\":200}");
            yb = JSONObject.parseObject(PlDataMakeUtils.getYbParentMatch(y_str).get(0).toString());
        } catch (Exception e) {
            logger.error("IM比赛内容详情获取异常！！！PMatchNo="+PMatchNo+">>>异常信息:"+ ExceptionUtil.getExceptionMessage(e));
        }
        return yb;

    }

    /*
    // 获取雷电竞的比赛内容详情接口
   */
    public static JSONObject get_ldj_content(String match_id) {
        try {
            String l_str = HttpClient.doGetCloseable(ldj_host+"/v2/odds?match_id=" + match_id,null);
            JSONObject l_json = new JSONObject();
            l_json = JSONObject.parseObject(l_str).getJSONObject("result");
            return l_json;
        }catch (Exception e){
            logger.error("雷电竞的比赛内容详情获取异常！！！match_id="+match_id+">>>异常信息:"+ ExceptionUtil.getExceptionMessage(e));
            e.printStackTrace();
        }
        return null;
    }

}
